// xc_lshop/business/order/order.js
var actbill = require('../model/business_bill')

Page({
  mixins: [require('../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    seachval: "",
    acttab: '0',
    ordertype: '0',
    isempty: false,
    navlist: [{
        "id": '0',
        name: "全部"
      },
      {
        "id": '-7',
        name: "七日订单"
      },
      {
        "id": '-8',
        name: "今日订单"
      },
      {
        "id": '-1',
        name: "待付款"
      },
      {
        "id": '1',
        name: "待发货"
      },
      {
        "id": '4',
        name: "已发货"
      },
      {
        "id": '12',
        name: "待退款"
      },
      {
        "id": '13',
        name: "已退款"
      },
      {
        "id": '14',
        name: "拒绝退款"
      },
      {
        "id": '10',
        name: "已完成"
      },
      {
        "id": '-3',
        name: "已关闭"
      },
    ],

  },

  onChangetabs: function (ev, isupdate) {
    if (isupdate) {
      this.setData({
        acttab: ev.detail.name
      })
    } else {
      this.data.acttab = ev.detail.name
    }
    var that = this;
    that.getpagelist(that, 1, {})
  },
  showdetail(e) {
    var status = e.currentTarget.dataset.status;
    var index = e.currentTarget.dataset.index;
    var name = 'modellist[' + index + '].showdetail';
    var updatestatus = '';
    if (status == 1) {
      updatestatus = false;
    } else {
      updatestatus = true;
    }
    this.setData({
      [name]: updatestatus
    })
  },
  onCancel: function (ev) {
    var that = this;
    this.setData({
      seachval: ""
    })
    this.getpagelist(that, 1)
  },
  onSearch(ev) {
    this.setData({
      seachval: ev.detail
    })
    var that = this;
    this.getpagelist(that, 1)
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },
  xcloaddata: function (options, config) {
    console.log("config555")
    console.log(config)

    var update = {};
    if (config.payment) {
      update['paymentconfig'] = config.payment
    }

    if (config.delivery_config) {
      update['deliveryconfig'] = config.delivery_config;

    } else {
      update['deliveryconfig'] = {
        chieftxt: "社区团长",
        expresstxt: "快递配送",
        intracitytxt: "同城配送",
        storetxt: "到店自提"
      }
    }
    if (options.opstatus) {
      update['acttab'] = options.opstatus;
    }
    if (options.ordertype) {
      update['ordertype'] = options.ordertype;
    }
    this.setData(update)


    var strwhere = {}
    // strwhere["status"] = 1
    var app = getApp();
    var that = this;
    app.xc_sys_config.authop.oppower("login").then(function (res) {
      if (res.status == 1) {
        that.getpagelist(that, 1, strwhere)
      }
    })
  },
  getpagelist(that, rest, strwhere) {
    if (rest == 1) {
      if (!strwhere) {
        strwhere = {}
      }

      strwhere["ordertype"] = this.data.ordertype;
      strwhere["status"] = this.data.acttab;
      strwhere["shopid"] = 0;
      strwhere["seachval"] = this.data.seachval;

      that.setData({
        modellist: [],
        isempty: false
      });
    }
    actbill.offset(that, rest, strwhere).then(function (result) {
      var updatemdoel = {};
      if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {
        if (result["obj"]["modellist"].length < 1) {
          updatemdoel["isempty"] = true
        } else if (rest == 1) {
          updatemdoel["modellist"] = result["obj"]["modellist"];
        } else {
          if (result["obj"]["modellist"].length > 0) {
            updatemdoel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
          }
        }
      }

      wx.stopPullDownRefresh();
      that.setData(updatemdoel);
    }, function () {

    });
  },
  optool(ev) {
    var op = ev.target.dataset.op
    var dataset = ev.currentTarget.dataset


    var item = dataset.item
    var index = dataset.index

    var that = this;
    switch (op) {
      case "copyall": {
        var data = ""
        data +="订单号："+item.ordernum+'\n';
        data +="商品：";
        for(var i in item.orderinfo){
          var attr=""
          if(item.orderinfo[i]['attrnameinfo']){
            for(var a in item.orderinfo[i]['attrnameinfo']){
              var attritem=item.orderinfo[i]['attrnameinfo'][a];
              attr+="【"+attritem.attrname.name+"】"
            }
          }
      
          data +=item.orderinfo[i]['name']+ attr +" x"+item.orderinfo[i]['num']+";";
        }
        data +="\n";
        if(item.discountprice){
          data +="卖家改价：-￥"+ (item.discountprice /100).toFixed(2)+'\n';
        }
        if(item.vipcutprice){
          data +="vip优惠：-￥"+ (item.vipcutprice /100).toFixed(2)+'\n';
        }
        if(item.couponmoney){
          data +="优惠券：-￥"+ (item.couponmoney /100).toFixed(2)+'\n';
        }
        data +="金额：￥"+ (item.totalprice /100).toFixed(2)+'\n';
        data +="下单时间："+ item.createtime+'\n';
        if(item.pickuptime){
          data +="自取时间："+ item.pickuptime+'\n';
        }
        if(item.choosetime){
          data +="配送时间："+ item.choosetime+'\n';
        }
        var deliveryconfig=this.data.deliveryconfig;
        var modename=""
        if((item.distributionmode & 1)==1){
          modename=deliveryconfig.expresstxt?deliveryconfig.expresstxt:"快递配送";
        }else if((item.distributionmode & 2)==2){
          modename=deliveryconfig.chieftxt?deliveryconfig.chieftxt:"社区团长"+"-"+ ((item.distributionmode & 16)==16?'配送':'自提');
        }else if((item.distributionmode & 4)==4){
          modename=deliveryconfig.chieftxt?deliveryconfig.chieftxt:"社区团长"+"-"+((item.distributionmode & 16)==16?'配送':'自提')
        }else if((item.distributionmode & 8)==8){
          modename=deliveryconfig.intracitytxt?deliveryconfig.intracitytxt:'同城配送'
        }

        data +="配送方式："+ modename +'\n';
        var paymentconfig=this.data.paymentconfig
        if(item.clubinfo){
          data +="团点地址："+ item.clubinfo.title +" "+ item.clubinfo.name+" "+ item.clubinfo.phone+" "+ item.clubinfo.province+" "+ item.clubinfo.city+" "+ item.clubinfo.county+" "+ item.clubinfo.addrinfo +'\n';
        }
      
        if((item.distributionmode & 25)!=0){
          data +="收件地址："+ (item.name +" "+item.phone+" "+ item.province +" "+ item.city+" "+ item.county+" "+ item.addrinfo +" "+ (item.addrmoreinfo?item.addrmoreinfo:''))+'\n';
        }else if(item.type!=2 && item.ordertype!=12){
          data +="个人信息："+ item.name + item.phone+'\n';
        }

        data +="支付方式："+ (item.paytype==0?'零元支付':item.paytype==1?'微信支付':item.paytype==2?(paymentconfig.balancepayname?paymentconfig.balancepayname:'余额')+'支付':'') +'\n';

        if(item.status>=4 && item.type!=2 && item.ordertype!=12){
          data +="快递信息："+ item.expressname + item.expressnum +'\n';
        }



        if(item.remark){
          data +="备注："+ item.remark+'\n';
        }

        if(item.refundstatus!=-1 && item.refundapplyinfo){
          data +="申请时间："+ item.refundapplyinfo.createtime+'\n';
          data +="申请原因："+ "【"+item.refundapplyinfo.reason+"】"+item.refundapplyinfo.remark+'\n';
          data +="申请状态："+ item.refundapplyinfo.status==1?'已同意':item.refundapplyinfo.status==3?'已拒绝':'申请中'+'\n';
          if(item.refundapplyinfo.status==3){
          data +="拒绝原因："+ item.refundapplyinfo.refuse_reason?item.refundapplyinfo.refuse_reason:'无'+'\n';
          }
        }

        if(item.refundstatus==1){
          data +="退款金额：￥"+ (item.refundfree /100).toFixed(2)+'\n';

        }


        wx.setClipboardData({
          data: data,
          success(res) {
            wx.showToast({
              title: "复制成功",
            })

          }
        })
        break;
      }
      case "deliver": {
        that.selectComponent("#businessdeliver").showdeliver("deliver", index, item)
        break;
      }
      case "editdeliver": {
        that.selectComponent("#businessdeliver").showdeliver("editdeliver", index, item)
        break;
      }
      case "refund": {
        that.selectComponent("#businesspopup").showrefund('refund', index, item)
        break;
      }
      case "refuse": {
        that.selectComponent("#businesspopup").showrefund('refuse', index, item)
        break;
      }
      case "cancel": {
        wx.showModal({
          title: '取消订单',
          content: '确定要取消当前订单？',
          showCancel: true, //是否显示取消按钮
          cancelText: "否", //默认是“取消”
          confirmText: "是", //默认是“确定”
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定
              that.cancelorder(item.id, index)

            }
          },
          fail: function (res) {}, //接口调用失败的回调函数
          complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
        })
        break;
      }
      case "changeprice": {
        that.selectComponent("#businesspopup").showrefund('changeprice', index, item)
        break;
      }
      case "finishbill": {
        wx.showModal({
          title: '确认收货',
          content: '请确认当前订单已收货？',
          showCancel: true, //是否显示取消按钮
          cancelText: "否", //默认是“取消”
          confirmText: "是", //默认是“确定”
          success: function (res) {
            if (res.cancel) {
              //点击取消,默认隐藏弹框
            } else {
              //点击确定
              that.finishbill(item.id, index)
            }
          },
          fail: function (res) {}, //接口调用失败的回调函数
          complete: function (res) {}, //接口调用结束的回调函数（调用成功、失败都会执行）
        })
        break;
      }
    }
  },
  bindKeyInput: function (e) {
    this.setData({
      inputValue: e.detail.value
    })
  },
  eventpopup(e) {
    var that = this;
    var op = e.detail.op;
    var index = e.detail.index;
    var refundstatus = 'modellist[' + index + '].refundstatus';

    if (op == 'refund') {
      var refundata = e.detail.refundata;
      var refundfree = 'modellist[' + index + '].refundfree'
      var refundmoney = (refundata['balance'] * 1 + refundata['online'] * 1) * 100
      that.setData({
        [refundstatus]: e.detail.refundstatus + '',
        [refundfree]: refundmoney
      })
    } else if (op == 'refuse') {
      var refusedata = e.detail.refusedata;
      var refundstatus = 'modellist[' + index + '].refundstatus';
      var refundapplyinfo = 'modellist[' + index + '].refundapplyinfo.refuse_reason';
      var refundapplystatus = 'modellist[' + index + '].refundapplyinfo.status';

      that.setData({
        [refundstatus]: e.detail.refundstatus + '',
        [refundapplyinfo]: refusedata.reason,
        [refundapplystatus]: 3
      })
    } else if (op == 'changeprice') {
      var pricedata = e.detail.pricedata;
      var discountprice = 'modellist[' + index + '].discountprice';
      that.setData({
        [discountprice]: pricedata.discountprice * 100
      })
    }

  },
  eventdeliver(e) {


    var that = this;
    var index = e.detail.index;
    var status = e.detail.status;

    var formdata = e.detail.formdata
    var expressname = 'modellist[' + index + '].expressname';
    var expressnum = 'modellist[' + index + '].expressnum'
    var expresscode = 'modellist[' + index + '].expresscode'


    that.setData({
      [expressname]: formdata['expressname'],
      [expressnum]: formdata['expressnum'],
      [expresscode]: formdata['expresscode']
    })

    if (e.detail.op == 'deliver') {
      that.actback(index, status)
    }





    // var formdata = e.detail.formdata
    // var expressname = 'modellist[' + index + '].expressname';
    // var expressnum = 'modellist[' + index + '].expressnum'
    // var expresscode = 'modellist[' + index + '].expresscode'


    // that.setData({
    //   [expressname]: formdata['expressname'],
    //   [expressnum]: formdata['expressnum'],
    //   [expresscode]: formdata['expresscode']
    // })
    // if (this.data.acttab == 0) {
    //   var modellist = 'modellist[' + index + '].status'
    //   that.setData({
    //     [modellist]: status+''
    //   })

    // } else {
    //   var list = this.data.modellist;
    //   list.splice(index, 1)
    //   that.setData({
    //     modellist: list
    //   })

    // }




  },
  preview(e) {
    var dataset = e.currentTarget.dataset;
    var imgList = dataset.urls;
    var src = imgList[dataset.idx]
    wx.previewImage({
      current: src, // 当前显示图片的http链接
      urls: imgList // 需要预览的图片http链接列表
    })
  },
  //确认收货
  finishbill(id, index) {
    var that = this;
    actbill.finishbill(id).then(res => {
      if (res["status"] == 1) {
        wx.showToast({
          icon: 'success',
          title: "收货成功",
        })
        that.actback(index, 9)
      } else {
        wx.showToast({
          icon: 'error',
          title: res["message"],
        })
      }
    })
  },
  //取消订单
  cancelorder(id, index) {
    var that = this;
    actbill.ordercancel(id).then(res => {
      if (res["status"] == 1) {
        wx.showToast({
          icon: 'success',
          title: "取消成功",
        })
        that.actback(index, -3)
      } else {
        wx.showToast({
          icon: 'error',
          title: res["message"],
        })
      }
    })
  },
  //产品跳转
  pronavigateTo(e) {
    var dataset = e.currentTarget.dataset;
    var purl = '../../shop/pro/proinfo?id=' + dataset.id;
    if (dataset.activityid) {
      purl += "&activityid=" + dataset.activityid + "&activitytype=" + dataset.activitytype;
    }
    wx.navigateTo({
      url: purl,
    })
  },
  //执行成功返回,修改列表数据
  actback(index, status) {
    var that = this;
    if (that.data.acttab == "0") {
      var modelstatus = 'modellist[' + index + '].status';
      that.setData({
        [modelstatus]: status
      })
    } else {
      var list = this.data.modellist;
      list.splice(index, 1)
      that.setData({
        modellist: list
      })
    }
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    var that = this
    that.getpagelist(that, -1)
  },


  back() {
    wx.navigateBack({
      delta: 1
    })
  }
})